<?php

namespace app\logic\controller;

use app\api\controller\AlibaUploadToken;
use OSS\Core\OssException;
use OSS\Core\OssUtil;
use OSS\OssClient;

class Uploads
{
    /***
     * 临时AK
     */
    const  STS_AK="LTAI5tFfnCEUJLW1yndLKLZB";
    /***
     * AK
     */
    const   AK="LTAI5tJwyoXgd9bJvvQfvexW";


    const  SECRET="w9ZRRQ1svHLhYF8jM1zpXjYkwQeGOW";
    const  STS_SECRET="NhRzRGFjsIlxElurfHwHHTUMAo16Hw";

    public function UploadExcel($file_address,$type)
    {


        $result = AlibaUploadToken::token(self::STS_AK, self::STS_SECRET);

        if ($result['code'] == 200) {
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            $securityToken= $result['SecurityToken'];
            $accessKeyId= $result['AccessKeyId'];
            $accessKeySecret= $result['AccessKeySecret'];
// Endpoint以杭州为例，其它Region请按实际情况填写。
            $endpoint = "oss-cn-chengdu.aliyuncs.com";
// 填写Bucket名称，例如examplebucket。
            $type=='file' ? $oss='anim-resource.coreanim.com':$oss = 'anim-goods.coreanim.com';

            $type=='file' ? $bucket = "anim-resource" : $bucket = "anim-goods";
            if (empty($oss)) {
                $msg = [
                    'code' => 41002,
                    'msg' => '空间不存在',
                ];

                return $msg;
            }
            $name = '';
            switch ($type) {

                case 'image':
                    $address = 'images';
                    break;
                case 'video':
                    $address = 'videos';
                    break;
                case 'file':
                    $address = 'files';
                    $name = 'CoreAnim_';
                    break;
                default:
                    $address = $type;
                    break;

            }
            $type = getExt1($file_address); //获取文件后缀地址
            $pic = $name . md5(time() . rand(1113, 9999)) . '.' . $type;
            $curl_address = "upload/$address/" . date('Ymd');
            $path = public_path() . $curl_address;
            mkFolder($path);
            $object = $path . '/' . $pic;
            geturlpic($file_address, $object);
// <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
// 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。



            if (filesize($object)> 1024 * 1024 * 100) {


                /**
                 *  步骤1：初始化一个分片上传事件，获取uploadId。
                 */
                try {
                    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);

                    //返回uploadId。uploadId是分片上传事件的唯一标识，您可以根据uploadId发起相关的操作，如取消分片上传、查询分片上传等。
                    $uploadId = $ossClient->initiateMultipartUpload($bucket, $object);
                } catch (OssException $e) {
                    $msg = [
                        'code' => 41001,
                        'msg' => $e->getMessage()
                    ];
                    return $msg;

                }
                /*
                * 步骤2：上传分片。
                */

                $partSize = 100 * 1024 * 1024;
                $uploadFile = $file_address;
                $uploadFileSize = filesize($uploadFile);
                $pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
                $responseUploadPart = array();
                $uploadPosition = 0;
                $isCheckMd5 = true;
                foreach ($pieces as $i => $piece) {
                    $fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
                    $toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
                    $upOptions = array(
                        // 上传文件。
                        $ossClient::OSS_FILE_UPLOAD => $uploadFile,
                        // 设置分片号。
                        $ossClient::OSS_PART_NUM => ($i + 1),
                        // 指定分片上传起始位置。
                        $ossClient::OSS_SEEK_TO => $fromPos,
                        // 指定文件长度。
                        $ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
                        // 是否开启MD5校验，true为开启。
                        $ossClient::OSS_CHECK_MD5 => $isCheckMd5,
                    );

                    try {
                        // 开启MD5校验。
                        if ($isCheckMd5) {
                            $contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
                            $upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
                        }
                        // 上传分片。
                        $responseUploadPart[] = $ossClient->uploadPart($bucket, $object, $uploadId, $upOptions);
                    } catch (OssException $e) {
                        $msg = [
                            'code' => 41001,
                            'msg' => $i . $e->getMessage()
                        ];
                        return $msg;

                    }

                }


// $uploadParts是由每个分片的ETag和分片号（PartNumber）组成的数组。
                $uploadParts = array();
                foreach ($responseUploadPart as $i => $eTag) {
                    $uploadParts[] = array(
                        'PartNumber' => ($i + 1),
                        'ETag' => $eTag,
                    );
                }
                /**
                 *
                 *
                 * 步骤3：完成上传。
                 */
                try {
                    // 执行completeMultipartUpload操作时，需要提供所有有效的$uploadParts。OSS收到提交的$uploadParts后，会逐一验证每个分片的有效性。当所有的数据分片验证通过后，OSS将把这些分片组合成一个完整的文件。
                    $ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts);
                } catch (OssException $e) {
                    $msg = [
                        'code' => 41001,
                        'msg' => $e->getMessage()
                    ];

                    return $msg;
                }
                $msg = [
                    'code' => 200,
                    'msg' => 'success',
                    'url' => $oss,
                    'path' => $object
                ];

                return $msg;

            } else {

                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);

                try {
                    $ossClient->uploadFile($bucket, $object, $file_address);

                } catch (OssException $e) {

                    $msg = [
                        'code' => 41001,
                        'msg' => $e->getMessage()
                    ];


                    return $msg;
                }

                $types = 'image';
                if ($type == "jpg" || $type == "jpeg" || $type == "png" || $type == "gif") {
                    $types = 'image';
                } elseif ($type == "mp4") {
                    $types = 'video';
                } elseif ($type == "zip" || $type == "rar" || $type == "7z") {
                    $types = 'file';
                }




                $msg = [
                    'code'=>200,
                    'data'=>[
                        'url' => $oss,
                        'path' => $curl_address . '/' . $pic,
                        'type' => $types,
                        'size' => filesize($object),
                     ]
                ];


                return $msg;
            }

        }else{
            return $result;
        }
    }


}